package com.apes.scm.masterdata.stock.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.Name;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.model.PartySerialNumber;
import com.apes.scm.masterdata.party.repository.PartySerialNumberRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;

/**
 * 功能：仓库库区
 *
 * @author xul
 * @create 2018-01-26 15:26
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = Location.CONST_TABLE_NAME)
public class Location extends Model {
    public static final String CONST_TABLE_NAME = "mas_location";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = "mas_location_sequence", name = "仓库库区", padding = 2, prefix = "%(depot)", suffix = "%(usage)")
    @Comment("库区编码")
    private String id;

    @Column(name = "name", length = 120, nullable = false)
    @Comment("库区名称")
    private String name; //库区名称

    @NotNull
    @Name
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    @Comment("公司编码")
    private PartyRole company; //公司

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "depot_id", referencedColumnName = "id")
    @Comment("逻辑仓库编码")
    private Depot depot; //逻辑仓库

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "phy_depot_id", referencedColumnName = "id")
    @Comment("物理仓库编码")
    private PhyDepot phyDepot; //物理仓库

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "usage_id", referencedColumnName = "id")
    @Comment("库区类型编码")
    private StockUsage usage; //库区类型

    @Column(name = "sales_auto_delivery", nullable = false, columnDefinition = "number(1,0) default 1")
    @Comment("销售自动发货编码")
    private boolean salesAutoDelivery; //销售自动发货

    @Column(name = "valid", nullable = false)
    @Comment("有效")
    private boolean valid; //有效

    @Column(name = "ORIGIN", length = 20)
    @Comment("外部ID")
    private String origin; //外部ID

    @Name
    @Transient
    private Enumeration depotLevel; // 仓库级别

    public Enumeration getDepotLevel() {
        if (depot == null) return null;
        return depot.getDepotLevel();
    }
    @Name
    @Transient
    private Dept dept; // 仓库所属部门

    public Dept getDept() {
        if (depot == null) return null;
        return depot.getDept();
    }
    /**
     * 判断当前仓库是否带安库
     *
     * @return
     */
    public boolean checkProductRuleLocation() {
        if (this.getUsage().isProductRule()) return true;
        return false;
    }

    public String obtainLocationId(Location location) {
        //获取逻辑仓库编码
        PartySerialNumber serialNumber = SpringManager.getBean(PartySerialNumberRepository.class).findOne(
                JpaDsl.toCriteriaByEq(
                        "companyId", location.getCompany().getId())
        ).orElse(null);
        if (serialNumber == null) {
            throw new RuntimeException(String.format("公司[%s][%s]不存在于公司维度自增编码流水号记录表，无法生产新的仓库库区编码，请检查公司是否存在！", location.getCompany().getId(), location.getCompany().getName()));
        }
        //逻辑仓库编码+1后保存
        int locationId = serialNumber.getLocationId() + 1;
        serialNumber.setLocationId(locationId);
        serialNumber = SpringManager.getBean(PartySerialNumberRepository.class).saveAndFlush(serialNumber);
        return location.getDepot().getId() + String.format("%2d", serialNumber.getLocationId()).replace(" ", "0") + location.getUsage().getId();
    }

}
